function [position,isterminal,direction] = At_Periapsis(t,S)
GM_sun=1.327124400*10^(11);     %Sun
GM_earth=3.986004418*10^(5);    %Earth
GM_moon = 4.9048695*10^(3);     %Moon
%[km^3/s^2] Gravitational Parameters

u_se = GM_earth / (GM_earth+GM_sun);
u_em = GM_moon / (GM_moon+GM_earth);
% positionMoon = 1-u_em;

R = S(1:3);
V = S(4:6);


x = S(1);
y = S(2);
z = S(3);
xdot = S(4);
ydot = S(5);
zdot = S(6);

% if x>0.3
%     position = 1;
%     isterminal = 0;
%     direction = 0;
% else
%     angle = acos(dot(R,V)/(norm(V)*norm(R))) * 180 / pi;
%     position = angle - 90;
%     isterminal = 1;
%     direction = 0;
% end

if x>0.3
    position = 1;
    isterminal = 0;
    direction = 0;
else
    dr1dt = 1/2*((x+u_em)^2+y^2+z^2)^(-1/2)*...
        2*(x+u_em)*xdot*...
        2*y*ydot*...
        2*z*zdot;
    position = dr1dt; % The value that we want to be zero
    isterminal = 1;  % Halt integration
    direction = 1;   % The zero can be approached from either direction
end
